import 'package:merchants/models/spu.dart';

class Sku {
  final String? id;
  final String? image;
  final int count;
  final String? description;
  final List<String>? attrValue;
  final double price;
  final List<Spu>? spu;

  Sku({
    required this.count,
    required this.price,
    this.id,
    this.image,
    this.description,
    this.attrValue,
    this.spu,
  });

  factory Sku.fromJson(Map<String, dynamic> json) {
    return Sku(
      id: json['_id'] as String?,
      image: json['image'] as String?,
      count: json['count'] as int? ?? 0,
      description: json['description'] as String?,
      attrValue:
          (json['attr_value'] as List<dynamic>?)
              ?.map((item) => item['_id'] as String)
              .toList() ??
          [],
      price: (json['price'] as num?)?.toDouble() ?? 0.0,
      spu:
          (json['spu'] as List<dynamic>?)
              ?.map((item) => Spu.fromJson(item as Map<String, dynamic>))
              .toList() ??
          [],
    );
  }

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{'count': count, 'price': price};

    if (id != null) {
      map['_id'] = id;
    }
    if (image != null) {
      map['image'] = image;
    }
    if (description != null) {
      map['description'] = description;
    }
    if (attrValue != null) {
      map['attr_value'] = attrValue!.map((id) => {'_id': id}).toList();
    }

    return map;
  }
}
